<?php

namespace App\Http\Controllers;

use App\Http\Requests\Logic\Articles\ArticlesUpload;
use App\Http\Requests\Logic\Articles\ProjectCountDetailRequest;
use App\Http\Requests\Logic\Articles\ProjectCountRequest;
use App\Models\Article;
use App\Models\Project;
use App\Models\System\SysLog;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Repositories\ArticlesRepository;
use App\Http\Requests\Logic\Articles\ShowRequest;
use App\Http\Requests\Logic\Articles\QueryResource;
use App\Http\Requests\Logic\Articles\ArticlesCreate;
use App\Http\Requests\Logic\Articles\ArticlesUpdate;
use App\Http\Requests\Logic\Articles\ArticlesDestroy;
use Illuminate\Support\Facades\DB;

/**
 * 文章逻辑控制器
 *
 * Date: 03/05/2018
 * @author George
 * @package App\Http\Controllers
 */
class ArticlesController extends Controller
{
    protected $articlesRepository;

    /**
     * ArticlesController constructor.
     * @param ArticlesRepository $articlesRepository
     */
    public function __construct(
        ArticlesRepository $articlesRepository
    )
    {
        $this->articlesRepository = $articlesRepository;
    }

    /**
     * 获取文章资源列表
     *
     * Date: 2018/4/10
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(QueryResource $request)
    {
        $user = Auth::user();
        $company_id = $user->company_id;
        $limit = $request->get('paginate', 15);
        $title = $request->get('title', false);
        $time = $request->get('time', false);
        $author = $request->get('author', false);
        $articles = $this->articlesRepository->getArticles($title, $time, $author, $company_id, $limit);
        return success($articles);
    }

    /**
     * 根据文章Id 获取文章详情资源
     *
     * Date: 2018/4/10
     * @author Tenny
     * @param ShowRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(ShowRequest $request, $article)
    {
        $app = $request->get('app',false);
        $res = $this->articlesRepository->getArticlesDetails($article);
        if($app){
            $read = DB::table('article_user_pivot')->updateOrInsert(['user_id'=>$request->user()->id,'article_id'=>$article]);
        }
        return success($res);
    }


    /**
     * 新建articles资源
     *
     * Date: 2018/4/10
     * @author Tenny
     * @param ArticlesCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(ArticlesCreate $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        $attributes['company_id'] = $request->user()->company_id;
        $attributes['user_id'] = $request->user()->id;
        $articles = $this->articlesRepository->create($attributes);
        SysLog::log(Auth::user(),'心灵驿站模块',"新增文章");
        return stored($articles);
    }

    /**
     * 更新articles资源
     *
     * Date: 2018/4/10
     * @author Tenny
     * @param ArticlesUpdate $request
     * @param Article $article
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(ArticlesUpdate $request, Article $article)
    {
        $articlesAttr = $request->only([
            'title',
            'cover',
            'content',
        ]);
        $article->update($articlesAttr);
        SysLog::log(Auth::user(),'心灵驿站模块',"修改文章");
        return updated($article);
    }

    /**
     * 删除 articles 资源
     *
     * Date: 2018/4/10
     * @author Tenny
     * @param ArticlesDestroy $request
     * @param Article $article
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(ArticlesDestroy $request, Article $article)
    {
        $force = $request->get('force');
        $force ? $article->delete() : $article->forceDelete();
        SysLog::log(Auth::user(),'心灵驿站模块',"删除文章");
        return deleted();
    }

    /**
     * 上传心灵驿站封面图片
     *
     * Date: 2018/5/2
     * @author Tenny
     * @param ArticlesUpload $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload(ArticlesUpload $request)
    {
        $path = $request->file('cover')->store('cover');
        return success($path);
    }

    /**
     * 当前文章各个项目阅读率
     *
     * Date: 2018/5/29
     * @author Sam
     * @param ProjectCountRequest $request
     * @param $article
     * @return \Illuminate\Http\JsonResponse
     */
    public function projectCount(ProjectCountRequest $request,$article)
    {
        $projects = Project::query()->select(['name','id'])
            ->with(['users'=>function($q){$q->select(['id','name','project_id']);}])
            ->withCount('users')
            ->get()
            ->toArray();
        $read = DB::table('article_user_pivot')->where('article_id',$article)->get();
        foreach ($projects as $k => $v){
            $reading = 0;
            foreach ($v['users'] as $key => $val){
                foreach ($read as $kk => $vv){
                    if($vv->user_id==$val['id']){
                        $reading += 1;
                    }
                }
            }
            $projects[$k]['reading'] =round($v['users_count']>0?$reading/$v['users_count']:0,2);
        }
        return success($projects);
    }

    /**
     * 当前文章当前项目文章阅读详情
     *
     * Date: 2018/6/1
     * @author Sam
     * @param ProjectCountDetailRequest $request
     * @param $article
     * @param $project
     * @return \Illuminate\Http\JsonResponse
     */
    public function projectCountDetail(ProjectCountDetailRequest $request,$article,$project)
    {
        $users = User::query()->where('project_id',$project)->select('id','name')->get()->toArray();
        $read = DB::table('article_user_pivot')->where('article_id',$article)->get();
        foreach ($users as $k => $v){
            $status = 0;
            foreach ($read as $key => $val){
                if($val->user_id==$v['id']){
                    $status = 1;
                    break;
                }
            }
            $users[$k]['read'] = $status;
        }
        return success($users);
    }
}
